package jiaxa.com.jsbridge.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.lang.reflect.Type;
import java.util.ArrayList;


/**
 * Created by jiaxa on 2017/11/22.
 */


public class GsonUtil {
    /*
    * [{\"username\":\"test\"},{\"username\":\"test2\"}]
    * */
    public static <T> ArrayList<T> jsonArrayToList(String jsonArrayString, Type typeOfT) {
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(jsonArrayString).getAsJsonArray();
        ArrayList<T> list = new ArrayList<T>();
        for (JsonElement obj : jsonArray) {
            T entity = gson.fromJson(obj, typeOfT);
            list.add(entity);
        }
        return list;
    }
    /**
     * 将json字符串转换为对象
     * @param json 要裁剪的图片
     * @param typeOfT 类型
     */
    public static <T> T toObject(String json, Type typeOfT) {
        Gson gson = new Gson();
        T entity = gson.fromJson(json, typeOfT);
        return entity;
    }
    /**
     * 将json字符串转换为对象
     * @param object 要转换的对象
     */
    public static <T> String toJson(T object) {
        Gson gson = new Gson();
        String json = gson.toJson(object);
        return json;
    }
}
